//
//  QSOAuthViewController.m
//  SinaWeiBo
//
//  Created by apple on 16/5/30.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "QSOAuthViewController.h"
#import "QSUserAccount.h"
#import "QSUserAccountViewModel.h"

@interface QSOAuthViewController ()<UIWebViewDelegate>
/**
 *  webView
 */
@property (nonatomic, weak) UIWebView* webView;

@end

@implementation QSOAuthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 设置导航控制器的两个按钮
    [self setupNavUI];
    
    // 加载网页
    [self loadOAuthPage];
}

#pragma mark - 重写loadView方法
- (void)loadView
{
    // 初始化webView
    UIWebView *wView = [[UIWebView alloc] init];
    self.webView = wView;
    // 把view替换为webView
    self.view = self.webView;
    
    // 设置成为代理
    self.webView.delegate = self;
}

#pragma mark - 监听方法
/**
 *  退出登录授权页面
 */
- (void)close
{
    // 退出登录授权页面
    [self dismissViewControllerAnimated:YES completion:nil];
}

/**
 *  自动填充
 */
- (void)fullAccount
{
    // 执行js语句
    NSString *jsStr = @"document.getElementById('userId').value = '15914301475' , document.getElementById('passwd').value = 'chen12';";
    
    [self.webView stringByEvaluatingJavaScriptFromString:jsStr];
}
/**
 *  设置导航控制器的两个按钮
 */
- (void)setupNavUI
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"自动填充" style:UIBarButtonItemStylePlain target:self action:@selector(fullAccount)];
}

/**
 *  加载授权网页
 */
- (void)loadOAuthPage
{
    // 创建url
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@", kCLIENT_ID, kREDIRECT_URI];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    // 创建请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 加载请求
    [self.webView loadRequest:request];
}

#pragma mark - webView的代理方法
/**
 *  开始加载
 */
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    // 弹出加载框
    [QSSVProgressTool showLoadingView];
}

/**
 *  加载完成
 */
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    // 隐藏加载框
    [QSSVProgressTool hideLoading];
}

/**
 *  每次加载URL都会调用
 */
// 代理方法如果返回值是bool类型，一般表示 如果为true  表示当前对象可以正常 工作  否则就不能
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    QSLog(@"%@", request.URL);
    // 全路径字符串
    NSString *absoluteStr = request.URL.absoluteString;
    // 如果URL不包含回调地址，就都进行加载
    if (![absoluteStr hasPrefix:kREDIRECT_URI]) {
        return YES;
    }else{
        // 查询字符串
        NSString *queryStr = request.URL.query;
        // 判断查询字符串是否包含 `code=`
        NSString *prefixStr = @"code=";
        if ([request.URL.query hasPrefix:prefixStr]) {
            // 计算code值得起始位置
            NSInteger index = [queryStr rangeOfString:prefixStr].location + prefixStr.length;
            // 截取code(授权码)的值,可用来获取用户令牌（token）
            NSString *codeStr = [queryStr substringFromIndex:index];
            
            // 请求用户令牌
            __weak typeof(self) weakSelf = self;
            [[QSUserAccountViewModel alloc] loadAccessToken:codeStr finish:^(NSError *error) {
                QSLog(@"come here");
                
                // 退出授权界面
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
                
                // 跳转到主界面（发送通知）
                [[NSNotificationCenter defaultCenter] postNotificationName:AppSwitchRootViewControler object:@"welcome"];
            }];
            
            return NO;
        }
    }
    return NO;
}

/**
 *  加载失败
 */
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    // 判断是否因为用户中断
    if (error.code == 102) {
        // 隐藏加载框
        [QSSVProgressTool hideLoading];
    }else{
        [QSSVProgressTool showFailStatus:@"您的网络不给力"];
    }
}
@end
